package com.lwq.http.threads.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;

import com.lwq.http.utils.SendHttpUtils;
import com.lwq.http.utils.model.HttpParamsMap;
import com.lwq.http.utils.model.HttpResult;

/**
* @author 作者 linweiqiang
* @version 创建时间：2017年10月19日 上午11:07:08
* 类说明
*/
public class HttpThread implements Runnable {
	private CloseableHttpClient hc = null;
	private String uri = null;
	private Map<String,String> map = null;
	private HttpParamsMap hpm = null;
	private long sleepT = 0;
	private HttpResult hr = null;
	/**
	 * 请求线程
	 * @param hc CloseableHttpClient
	 * @param uri 请求地址
	 * @param map 请求参数
	 */
	public HttpThread(CloseableHttpClient hc,String uri ,Map<String,String> map , HttpParamsMap hpm ,HttpResult hr,long sleepT) {
		this.hc = hc;
		this.uri = uri;
		this.sleepT = sleepT;
		this.map = map;
		this.hpm = hpm;
		this.hr = hr;
		if(hpm!=null){
			this.map.putAll(this.hpm.getParams());
		}
	}
	@Override
	public void run() {
		System.out.println("=======");
		CloseableHttpResponse chr = null;
		HttpPost hp = null;
		try {
			hp =SendHttpUtils.sendPost(uri, map);
			chr = hc.execute(hp);
			if(hr!=null)
			hr.resultMethod(chr);
			Thread.sleep(sleepT);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			hp.releaseConnection();
			SendHttpUtils.closeableHttpResponse(chr);
		}
	}

}
